package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.mainframeSub;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.net.URL;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.Mainframe;

public class SystemTrayLoader {

	private boolean isSupported = false;
	private TrayIcon trayIcon;
	private Mainframe mainframe;
	
	public SystemTrayLoader(Mainframe mainframe){
		this.mainframe = mainframe;
	}

	public void makeaSystemTrayImage() {

		if (SystemTray.isSupported()) {
			this.isSupported = true;

			SystemTray tray = SystemTray.getSystemTray();
			URL pic = getClass().getResource("/trayIcon.png");
			Image image = Toolkit.getDefaultToolkit().getImage(pic);

			MouseListener mouseListener = new MouseListener() {

				public void mouseClicked(MouseEvent e) {
					if (e.getClickCount()==2) {
						mainframe.setVisible(true);
					}
				}

				public void mouseEntered(MouseEvent e) {
				}

				public void mouseExited(MouseEvent e) {
				}

				public void mousePressed(MouseEvent e) {
				}

				public void mouseReleased(MouseEvent e) {
				}
			};

			ActionListener exitListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.out.println("Exiting...");
					System.exit(0);
				}
			};

			PopupMenu popup = new PopupMenu();
			MenuItem defaultItem = new MenuItem("Exit");
			defaultItem.addActionListener(exitListener);
			popup.add(defaultItem);

			trayIcon = new TrayIcon(image, "Simple CMS", popup);

			trayIcon.setImageAutoSize(true);
			trayIcon.addMouseListener(mouseListener);

			try {
				tray.add(trayIcon);
			} catch (AWTException e) {
				System.err.println("TrayIcon could not be added.");
			}

		} else {

			// System Tray is not supported

		}

	}

	public void createSysTrayMessage(String title, String text) {

		if (isSupported) {
			
			this.trayIcon
					.displayMessage(title, text, TrayIcon.MessageType.INFO);
		}

	}
}
